package com.ourmovieguy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class NYTMovie {
	
	
	public NYTMovie(String name, String rating, String publication, String capsule, String baseurl) {
		m_name = name;
		m_rating = rating;
		m_publication = publication;
		m_capsule = capsule;
		m_baseurl = baseurl;
		m_imageurl = ""; //getImageUrl();
	}
	
	public String getImageUrl() {
		String line;
		try {
        BufferedReader in = new BufferedReader(new InputStreamReader(new URL(m_baseurl).openStream()));
        
        do{
             line = in.readLine();
             if (line != null){
            	if (line.contains("callout")) {
            	 for (String tok: line.split(" ")) {
            		 if (tok.contains("src")) {
            			 return tok.substring(4);
            		 }
            	 }
            	}
             }
        }while (line != null);
        } catch (IOException e) {
        	return "ERR" + e.toString();
        }
        return  "no image";
	}
	
	public String getName()
	{
		return m_name;
	}
	
	public String getRating()
	{
		return m_rating;
	}
	
	public String getPub()
	{
		return m_publication;
	}
	
	public String getUrl()
	{
		return m_baseurl;
	}
	
	public String toString() {
		String sb = "[";
		sb += m_name + " ";
		sb += m_rating + " ";
		sb += m_publication + " ";
		sb += m_capsule + m_baseurl;
		sb += m_imageurl + " ]";
		return sb;
	}
	
	public String toJSON() {
		String sb = "{\n";
		sb += "\"name\": \"" + m_name + "\", \n";
		sb += "\"rating\": \"" + m_rating + "\", \n";
		sb += "\"pub\": \""  + m_publication + "\", \n";
		sb += "\"summ\": \"" + m_capsule + "\",\n";
		sb += "\"url\": \""  + m_baseurl + "\",\n";
		sb += "\"image\": \"" + m_imageurl + "\"\n";
		sb += " }\n";
		return sb;
	}
	
	public String toSmallJSON() {
		String sb = "{\n";
		sb += "\"name\": \"" + m_name + "\", \n";
		sb += " }\n";
		return sb;
	}
	
	@PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private String m_name;

	@Persistent
	private String m_baseurl;
    
	@Persistent
	private String m_rating;
    
	@Persistent
	private String m_publication;
    
	@Persistent
	private String m_capsule;
    
	@Persistent
	private String m_imageurl;
}
